import { intercomRequest, intercomControl } from '@/api/gps/jt808/jt1078'
// //需要使用到的音频格式编码引擎的js文件统统加载进来，这些引擎文件会比较大
// import 'recorder-core/src/engine/mp3'
// import 'recorder-core/src/engine/mp3-engine'
// import 'recorder-core/src/engine/pcm'
// //可选的扩展
// import 'recorder-core/src/extensions/waveview'
// import 'recorder-core/src/extensions/wavesurfer.view'
// import 'recorder-core/src/extensions/frequency.histogram.view'
// import 'recorder-core/src/extensions/lib.fft'
// import recorder from './recorder'
// import pcmPlayer from './pcmPlayer'
import { jt1078Heart } from '@/api/gps/command'
import PCMPlayer from 'pcm-player'
import Recorder from '@/utils/gps/audio/index'
import Player from '@/utils/gps/audio/player'

let gPcmPlayer, gRecorder, gWs
let heartTimer

let recorder: Recorder;
let playTimer: any = null;

// export function prepareMedia() {
//   return new Promise((resolve, reject) => {
//     // console.log('cb', navigator.mediaDevices.getUserMedia)
//     // @ts-ignore
//     if (!navigator.mediaDevices.getUserMedia) {
//       reject('浏览器不支持录音')
//       return
//     }
//     // @ts-ignore
//     navigator.mediaDevices
//       .getUserMedia({ audio: true })
//       .then((stream) => {
//         console.log('getUserMedia', stream)
//         resolve(stream)
//       })
//       .catch((e) => {
//         // console.log('other', e)
//         reject(e)
//       })
//   })
// }
export function recordStartStop(start) {
  const config = {
    sampleBits: 16,
    sampleRate: 8000,
    numChannels: 1,
    compiling: true,       // 是否开启边录音边转化（后期改用web worker）
  }
  if (!recorder) {
    recorder = new Recorder(config);
    recorder.onprogress = (params) => {
      // console.log(recorder.duration);
      // console.log(recorder.fileSize);

      //duration: 0.08533333333333333
      // fileSize: 1364
      // vol : 0

      // this.setState({
      //   duration: params.duration.toFixed(5),
      //   fileSize: params.fileSize,
      //   vol: params.vol.toFixed(2)
      // });

      // 此处控制数据的收集频率
      if (config.compiling) {
        // console.log('音频总数据：', params.data);
        // gPcmPlayer.feed(params.data[0]);
        gWs.send(params.data[0])
      }
    }

    recorder.onplay = () => {
      console.log('%c回调监听，开始播放音频', 'color: #2196f3')
    }
    recorder.onpauseplay = () => {
      console.log('%c回调监听，暂停播放音频', 'color: #2196f3')
    }
    recorder.onresumeplay = () => {
      console.log('%c回调监听，恢复播放音频', 'color: #2196f3')
    }
    recorder.onstopplay = () => {
      console.log('%c回调监听，停止播放音频', 'color: #2196f3')
    }
    recorder.onplayend = () => {
      console.log('%c回调监听，音频已经完成播放', 'color: #2196f3')
      // 播放结束后，停止绘制canavs
      // this.stopDrawPlay();
    }

    // 定时获取录音的数据并播放
    // config.compiling && (playTimer = setInterval(() => {
    //   if (!recorder) {
    //     return;
    //   }

    //   let newData = recorder.getNextData();
    //   console.log('newData.length', newData.length)
    //   if (!newData.length) {
    //     return;
    //   }
    //   let byteLength = newData[0].byteLength
    //   let buffer = new ArrayBuffer(newData.length * byteLength)
    //   let dataView = new DataView(buffer)

    //   // 数据合并
    //   for (let i = 0, iLen = newData.length; i < iLen; ++i) {
    //     for (let j = 0, jLen = newData[i].byteLength; j < jLen; ++j) {
    //       dataView.setInt8(i * byteLength + j, newData[i].getInt8(j))
    //     }
    //   }

    //   // // 将录音数据转成WAV格式，并播放
    //   // let a = encodeWAV(dataView, config.sampleRate, config.sampleRate, config.numChannels, config.sampleBits)
    //   // let blob: any = new Blob([a], { type: 'audio/wav' });
    //   // blob.arrayBuffer().then((arraybuffer) => {
    //   //   Player.play(arraybuffer);
    //   // });
    // }, 3000))
    recorder.start().then(() => {
      console.log('开始录音');
    }, (error) => {
      console.log(`异常了,${error.name}:${error.message}`);
    });
  } else {
    recorder.stop();
    recorder.destroy();
    // recorder = null
  }
  // 开始绘制canvas
  // this.drawRecord();
  return recorder
}

export function handIntercomStart(imei: string, channel: number, stream: any) {
  return new Promise((resolve, reject) => {
    intercomRequest(imei, channel)
      .then((res: any) => {
        if (res.code === 0) {
          let url = res.data.wsUrl2
          let heartKey = res.data.heartKey
          // gPcmPlayer = new pcmPlayer({
          //   encoding: '16bitInt',
          //   channels: 1,
          //   sampleRate: 8000,
          //   flushingTime: 1000
          // })

          gPcmPlayer = new PCMPlayer({
            inputCodec: 'Int16',
            channels: 1,
            sampleRate: 8000,
            flushTime: 500,
            fftSize: 2048,
            onended: () => { // 监听播放结束

            }
          })
          // gRecorder = recorder.createRecord(stream)
          createWs(url)
          resolve('')
          startHeart(heartKey)
          //   reject(new Error('录音失败'))
        } else {
          //   this.$message.error(res.msg)
          reject(new Error(res.msg))
        }
      })
      .catch((e) => {
        reject(e)
      })
  })
}
/**
   * 心跳
   * @param heartKey
   */
function startHeart(heartKey: string) {
  jt1078Heart(heartKey).then(() => { })
  heartTimer = setTimeout(() => {
    startHeart(heartKey)
  }, 15000)
}

export function handIntercomStop(imei: string, channel: number) {
  return new Promise((resolve, reject) => {
    // if (gRecorder) {
    //   gRecorder.stop()
    //   gRecorder = null
    // }
    if (gPcmPlayer) {
      gPcmPlayer.destroy()
      gPcmPlayer = null
    }
    if (gWs) {
      gWs.close()
    }
    if (heartTimer) {
      clearInterval(heartTimer)
      heartTimer = null
    }
    intercomControl(imei, channel)
      .then((res: any) => {
        if (res.code === 0) {
          resolve('')
          //   intercomAudio = null
        } else {
          //   this.$message.error(res.msg)
          reject(new Error(res.msg))
        }
      })
      .catch((e) => {
        reject(e)
      })
  })
}
function createWs(url: string) {
  // @ts-ignore
  var ws = new WebSocket(url)
  ws.binaryType = 'arraybuffer' //传输的是 ArrayBuffer 类型的数据
  ws.onopen = (event) => {
    // console.log(this.gRecorder)
    // gRecorder.start((audioData) => {
    //   // ws.binaryData = 'blob'
    //   // console.log('gRecorder', audioData)
    //   ws.send(audioData)
    // })
  }
  ws.onclose = (evt) => {
    console.log('Connection closed......', evt)
    closeWs()
  }
  ws.onerror = () => {
    console.log('ws连接错误!' + new Date().toUTCString())
    closeWs()
  }
  ws.onmessage = (evt) => {
    receiveWsData(evt.data)
  }
  gWs = ws
}
function closeWs() {
  console.log('ws close')
  gWs.close()
}

function receiveWsData(data: ArrayBuffer) {
  // console.log('gPcmPlayer', data.byteLength)
  // if (data.byteLength === 640) {
  // var buf = new Uint16Array(data)
  var buf = new DataView(data)
  // var buf = new ArrayBuffer(data)
  // console.log('gPcmPlayer', buf.byteLength)
  gPcmPlayer.feed(buf)
  // }
}
